package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.mainConsult.ConsultEvaluateDetailActivity;
import com.digitalchina.lxnsy.activity.mainConsult.LiteratureListActivity;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.api.BusinessExpert;
import com.digitalchina.lxnsy.api.BusinessReward;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.ExpertNewVO;
import com.digitalchina.lxnsy.entity.LiteratureVO;
import com.digitalchina.lxnsy.entity.PayVO;
import com.digitalchina.lxnsy.entity.ServiceAssessVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.JointImageUrl;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.ExpertsDetailHolder;
import com.digitalchina.lxnsy.wxapi.WXPayEntryActivity;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hedgehog.ratingbar.RatingBar;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.lzy.okhttputils.model.HttpParams;

import org.sufficientlysecure.htmltextview.HtmlTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 专家详情 Created by zy on 2018/1/13.
 */

public class ExpertsDetailActivity extends BaseActivity {
    @Bind(R.id.tv_text)
    TextView tvText;
    private View headView;                            // 头布局
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.expert_details_consultation)
    LinearLayout ivConsultation;
    private TextView expand;        //简介展开
    private TextView expand2;    //机构展开

    private TextView expertName;                            // 专家姓名
    private SimpleDraweeView expertDetailsIvExpertAvatar;        // 专家头像
    private TextView address;                            // 专家地址
    private TextView expertTitles;                        // 专家职称
    private RatingBar expertDetailsRatingbar;                // 评级
    private TextView askNum;                                // 提问量
    private TextView replyNum;                            // 回复数
    private TextView studentNum;                            // 学员数
    private HtmlTextView expertDirection;                    // 领域
    private TextView expertResult;                        // 专家简介
    private TextView introduction;                        // 机构简介
    private List<ExpertNewVO> expertVOList = new ArrayList<>();
    private RecyclerArrayAdapter adapter;
    private ExpertNewVO expertVO;
    Map<String, Object> map = new HashMap<>();
    private String url = "";
    private boolean flag; //简介是否展开
    private boolean flagIntro; //机构是否展开

    private TextView tvRewardNum, tvCoinNum;  // 打赏人数 收到农币
    private ImageView ivReward; // 打赏图标
    private LinearLayout layoutHisReward; //  打赏历史

    private TextView tvTips, btnTips; // 咨询提示
    private TextView tvMore; // 更多文献
    private boolean flagTips; //机构是否展开

    private LinearLayout layoutEvaluateHead, layoutLiteratureHead;//父容器head
    private LinearLayout layoutEvaluate, layoutLiterature;//父容器view

    private String id = "";

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_expert_detail);
        setTitle("专家详情");
        setRightImage(R.drawable.ic_service_share);
    }

    @Override
    public void initMember() {

        map = (Map<String, Object>) getIntent().getSerializableExtra("map");

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ExpertsDetailHolder(parent);
            }
        });

        headView = LayoutInflater.from(this).inflate(R.layout.view_expert_detail, null);
        expertName = headView.findViewById(R.id.expert_details_tv_expert_name);
        expand = headView.findViewById(R.id.expand_btn);
        expand2 = headView.findViewById(R.id.in_expand_btn);
        expertDetailsIvExpertAvatar = headView.findViewById(R.id.expert_details_iv_expert_avatar);
        address = headView.findViewById(R.id.address);
        expertTitles = headView.findViewById(R.id.expert_details_tv_expert_titles);
        expertDetailsRatingbar = headView.findViewById(R.id.expert_details_ratingbar);
        askNum = headView.findViewById(R.id.item_expert_list_tv_ask_num);
        replyNum = headView.findViewById(R.id.item_expert_list_tv_reply_num);
        studentNum = headView.findViewById(R.id.item_expert_list_tv_student_num);
        expertDirection = headView.findViewById(R.id.expert_details_tv_research_direction);
        expertResult = headView.findViewById(R.id.expert_details_tv_research_result);
        introduction = headView.findViewById(R.id.introduction);
        tvTips = headView.findViewById(R.id.tv_tips);
        btnTips = headView.findViewById(R.id.btn_tips);
        tvMore = headView.findViewById(R.id.tv_more);

        tvRewardNum = headView.findViewById(R.id.tv_reward_num);
        tvCoinNum = headView.findViewById(R.id.tv_coin_num);
        ivReward = headView.findViewById(R.id.iv_reward);
        layoutHisReward = headView.findViewById(R.id.layout_history_reward);

        layoutEvaluateHead = headView.findViewById(R.id.layout_evaluate_head);
        layoutLiteratureHead = headView.findViewById(R.id.layout_literature_head);

        layoutEvaluate = headView.findViewById(R.id.layout_evaluate);
        layoutLiterature = headView.findViewById(R.id.layout_literature);

        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {

                return headView;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });


        if (map == null) {
            id = (String) getIntent().getSerializableExtra("id");
            // 调用专家详情接口 获取推荐列表
            BusinessExpert.getExpertDetailList(this, id, mHandler);
        } else {
            expertVO = (ExpertNewVO) map.get("ExpertVO");
            // 调用专家详情接口 获取推荐列表
            url = URL.URL_EXPERT_H5_CONTENT + expertVO.getId() + "&provinceName=" + (expertVO.getProvince() == null ? "" : expertVO.getProvince().getName()) +
                    "&cityName=" + (expertVO.getCity() == null ? "" : expertVO.getCity().getCityName());
            id = expertVO.getId();
            BusinessExpert.getExpertDetailList(this, id, mHandler);
//            setView(expertVO);
        }

        getProtocolInfo();
        getExpertUserServiceAssess();
        getExpertLiteratureInfoList();
        BusinessReward.queryRewardInfo(this, id, mHandler);
        BusinessAccount.saveUserBehaviorByMobile(this, Constant.BEHAVIOR_EXPERT_DETAIL, id, mHandler);
    }

    private void setView(ExpertNewVO expertVO) {

        if (expertVO == null)
            return;

        //咨询是否收费 0-免费 1-收费
        if ("1".equals(expertVO.getConsultIsFee())) {
            tvText.setText(String.format("图文咨询（%s元/次）", expertVO.getConsultFee()));
        } else {
            tvText.setText("免费咨询");
        }

        askNum.setText(expertVO.getQuestionNUm() == null ? "0" : expertVO.getQuestionNUm());
        replyNum.setText(expertVO.getAnswerNum() == null ? "0" : expertVO.getAnswerNum());
        studentNum.setText(expertVO.getStudentNum() == null ? "0" : expertVO.getStudentNum());
        address.setText((expertVO.getProvince() == null ? "" : expertVO.getProvince().getName()) + (expertVO.getCity() == null ? "" : expertVO.getCity().getName())
                + (expertVO.getCounty() == null ? "" : expertVO.getCounty().getName()));
        // 头像
        FrescoUtil.showImageSmall(expertVO.getPhoto() != null ? expertVO.getPhoto() : "", expertDetailsIvExpertAvatar);
        // 职位 title
        if (expertVO.getExpertTitle() != null) {
            expertTitles.setText(expertVO.getExpertTitle().getTitle());
        } else
            expertTitles.setVisibility(View.GONE);

        // 专家姓名
        expertName.setText(expertVO.getExpertName());
        // 研究方向
        if (expertVO.getExpertAreas() != null) {
            String s = "";
            for (int i = 0; i < expertVO.getExpertAreas().size(); i++) {
                s += expertVO.getExpertAreas().get(i).getExpertAreaType().getName() + "-"
                        + expertVO.getExpertAreas().get(i).getExpertAreaDirection().getName() + "\n";
            }
            expertDirection.setHtml(s);
        }
        // 研究成果
        expertResult.setText(expertVO.getExpertIntroduce() != null ? expertVO.getExpertIntroduce() : "");
        // 机构简介
        if (null != expertVO.getOrganization())
            introduction.setText(expertVO.getOrganization().getPersonalProfile() != null
                    ? expertVO.getOrganization().getPersonalProfile() : "");
        // 评价
        expertDetailsRatingbar.setStar((float) expertVO.getScore());


    }

    @Override
    public void addListener() {
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Map<String, Object> map = new HashMap<>();
                map.put("ExpertVO", adapter.getAllData().get(position));
                GotoUtil.gotoActivity(ExpertsDetailActivity.this, ExpertsDetailActivity.class, true, "map", map);
            }
        });

        expand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (flag) {
                    expertResult.setMaxLines(3);
                    expertResult.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
                    flag = false;
                    Drawable drawable = getResources().getDrawable(R.drawable.detail_expand_ico);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    expand.setCompoundDrawables(null, null, drawable, null);
                    expand.setText("展开");
                } else {
                    expertResult.setEllipsize(null);
                    expertResult.setSingleLine(flag);
                    flag = true;
                    Drawable drawable = getResources().getDrawable(R.drawable.detail_shrink_ico);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    expand.setCompoundDrawables(null, null, drawable, null);
                    expand.setText("收缩");
                }
            }
        });
        expand2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (flagIntro) {
                    introduction.setMaxLines(3);
                    introduction.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
                    flagIntro = false;
                    Drawable drawable = getResources().getDrawable(R.drawable.detail_expand_ico);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    expand2.setCompoundDrawables(null, null, drawable, null);
                    expand2.setText("展开");
                } else {
                    introduction.setEllipsize(null);
                    introduction.setSingleLine(flag);
                    flagIntro = true;
                    Drawable drawable = getResources().getDrawable(R.drawable.detail_shrink_ico);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    expand2.setCompoundDrawables(null, null, drawable, null);
                    expand2.setText("收缩");
                }
            }
        });

        btnTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (flagTips) {
                    tvTips.setMaxLines(3);
                    tvTips.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
                    flagTips = false;
                    Drawable drawable = getResources().getDrawable(R.drawable.detail_expand_ico);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    btnTips.setCompoundDrawables(null, null, drawable, null);
                    btnTips.setText("展开");
                } else {
                    tvTips.setEllipsize(null);
                    tvTips.setSingleLine(flag);
                    flagTips = true;
                    Drawable drawable = getResources().getDrawable(R.drawable.detail_shrink_ico);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    btnTips.setCompoundDrawables(null, null, drawable, null);
                    btnTips.setText("收缩");
                }
            }
        });

        ivConsultation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Utils.isLogin(ExpertsDetailActivity.this)) {
                    startActivityForResult(new Intent(ExpertsDetailActivity.this, LoginActivity.class), 1);
                    return;
                }

                if (expertVO == null)
                    return;


                //免费专家 直接咨询
                if ("0".equals(expertVO.getConsultIsFee())) {
                    GotoUtil.gotoActivity(ExpertsDetailActivity.this, ConsultIssueV2Activity.class, "single", expertVO);
                } else {
                    PayVO payVO = new PayVO();
                    payVO.setPrice(expertVO.getConsultFee());
                    payVO.setOrderNO(expertVO.getId());
                    payVO.setGoodsName("专家咨询费");
                    payVO.setType(4);
                    GotoUtil.gotoForResultActivity(ExpertsDetailActivity.this, WXPayEntryActivity.class, 136, "payVO", payVO);
                }

            }
        });


        ivReward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String, String> map = new HashMap<>();
                map.put("redType", "0");
                map.put("agriConsultId", id);
                GotoUtil.gotoForResultActivity(ExpertsDetailActivity.this, RewardActivity.class, 135, "map", map);
            }
        });

        layoutHisReward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GotoUtil.gotoActivity(ExpertsDetailActivity.this, RewardHistoryActivity.class, "agriConsultId", id);
            }
        });

        tvMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GotoUtil.gotoActivity(ExpertsDetailActivity.this, LiteratureListActivity.class, "expertId", id);
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 135:
                    BusinessReward.queryRewardInfo(this, id, mHandler);
                    break;
                case 136:
                    LogUtils.e(data.getSerializableExtra("orderNo").toString());
                    expertVO.setOrderNo(data.getSerializableExtra("orderNo").toString());
                    GotoUtil.gotoActivity(ExpertsDetailActivity.this, ConsultIssueV2Activity.class, "single", expertVO);
                    break;
            }
        }
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_GET_EXPERT_DETAILS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_QUERY_REWARD_INFO_SUCCESS:
                        String count = FastJsonUtil.getString(msg.obj.toString(), "count");
                        String money = FastJsonUtil.getString(msg.obj.toString(), "money");
                        tvRewardNum.setText(count + "");
                        tvCoinNum.setText(money + "");
                        break;
                    case MSG_S_0:
                        setView0(msg.obj.toString());
                        break;
                    case MSG_S_1:
                        setView1(msg.obj.toString());
                        break;
                    case MSG_S_2:
                        setView2(msg.obj.toString());
                        break;
                }
            }
        };
    }

    private void setView0(String json) {
        final List<ServiceAssessVO> list = FastJsonUtil.getListBean(json, "serviceAssessList", ServiceAssessVO.class);

        if (list == null)
            return;

        layoutEvaluate.removeAllViews();

        if(list.size()>0){
            layoutEvaluateHead.setVisibility(View.VISIBLE);
        }

        for (int i = 0; i < list.size(); i++) {
            View view = View.inflate(activity, R.layout.item_user_evaluate, null);
            SimpleDraweeView sdv = view.findViewById(R.id.sdv_head);
            TextView tvName = view.findViewById(R.id.tv_name);
            TextView tvOptsName = view.findViewById(R.id.tv_evaluate_tips);
            TextView tvScoreName = view.findViewById(R.id.tv_evaluate_lv);
            TextView tvContent = view.findViewById(R.id.tv_evaluate_content);
            TextView tvConsultContent = view.findViewById(R.id.tv_question);
            RelativeLayout layout = view.findViewById(R.id.layout_evaluate);
//            FrescoUtil.showImageSmall("",sdv);
            tvName.setText(list.get(i).getUserMobilePhone());
            tvOptsName.setText(list.get(i).getOptsName());
            tvScoreName.setText(list.get(i).getScoreName());
            tvContent.setText(list.get(i).getContent());
            tvConsultContent.setText(list.get(i).getConsultContent());

            final int finalI = i;
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    GotoUtil.gotoActivity(activity, ConsultEvaluateDetailActivity.class, "consultSessionId", list.get(finalI).getConsultSessionId());
                }
            });
            layoutEvaluate.addView(view);
        }
    }

    private void setView1(String json) {
        final List<LiteratureVO> list = FastJsonUtil.getListBean(json, "literatureInfoList", LiteratureVO.class);

        if (list == null)
            return;

        layoutLiterature.removeAllViews();

        if(list.size()>0){
            layoutLiteratureHead.setVisibility(View.VISIBLE);
        }

        for (int i = 0; i < list.size(); i++) {
            View view = View.inflate(activity, R.layout.item_expert_literature, null);
            TextView tvTitle = view.findViewById(R.id.tv_title);
            TextView tvTime = view.findViewById(R.id.tv_time);
            TextView tvBrowse = view.findViewById(R.id.tv_browse);
            RelativeLayout layout = view.findViewById(R.id.layout_literature);

            tvTitle.setText(list.get(i).getLiteratureName());
            tvTime.setText(list.get(i).getCreateTime());
            tvBrowse.setText("浏览量：" + list.get(i).getPageView());

            final int finalI = i;
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String, String> map = new HashMap<>();
                    map.put("url", URL.URL_GET_EXPERT_LITERATURE_INFO_DETAIL_H5 + "?literatureInfoId=" + list.get(finalI).getId() + "&userAccId=" + UserXML.getUserId(activity));
                    map.put("title", "专家文献");
                    GotoUtil.gotoActivity(activity, WebViewActivity.class, "map", map);
                }
            });
            layoutLiterature.addView(view);
        }
    }

    private void setView2(String json) {
        String content = FastJsonUtil.getString(json, "content");
        tvTips.setText(content);
    }

    @Override
    public void callBack(Object object) {
        expertVOList = FastJsonUtil.getListBean(object.toString(), "body", "relevantList",
                ExpertNewVO.class);
        expertVO = FastJsonUtil.getBean(object.toString(), "body", "expertInfo", ExpertNewVO.class);
        url = URL.URL_EXPERT_H5_CONTENT + expertVO.getId() + "&provinceName=" + (expertVO.getProvince() == null ? "" : expertVO.getProvince().getName()) +
                "&cityName=" + (expertVO.getCity() == null ? "" : expertVO.getCity().getCityName());
        setView(expertVO);
        adapter.clear();
        adapter.addAll(expertVOList);
    }

    @Override
    public void rightOnClick() {
       }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    //获取专家的用户评价
    public void getExpertUserServiceAssess() {
        HttpParams params = new HttpParams();
        params.put("expertId", id);
        params.put("page", String.valueOf(1));
        params.put("limit", String.valueOf(2));

        OkHttpUtil.post(activity, URL.URL_GET_EXPERT_USER_SERVICE_ASSESS, "", params, mHandler,
                MSG_S_0, MSG_F_0);
    }

    //获取专家文献
    public void getExpertLiteratureInfoList() {
        HttpParams params = new HttpParams();
        params.put("expertId", id);
        params.put("page", String.valueOf(1));
        params.put("limit", String.valueOf(2));

        OkHttpUtil.post(activity, URL.URL_GET_EXPERT_LITERATURE_INFO_LIST, "", params, mHandler,
                MSG_S_1, MSG_F_1);
    }

    //咨询提示
    public void getProtocolInfo() {
        HttpParams params = new HttpParams();
        params.put("type", "2");

        OkHttpUtil.post(activity, URL.URL_GET_PROTOCOL_INFO, "", params, mHandler,
                MSG_S_2, MSG_F_2);
    }


}
